<?php
/**
 * HTTP客户端类
 * 负责处理HTTP请求
 */
class HttpClient {
    /**
     * @var array 默认请求头
     */
    private $defaultHeaders = [];
    
    /**
     * 构造函数
     */
    public function __construct() {
        $this->defaultHeaders = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
            'accept-language:zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'sec-fetch-mode:navigate',
            'sec-fetch-site:none',
            'upgrade-insecure-requests:1',
            'sec-fetch-user:?1',
            'sec-ch-ua:"Not;A=Brand";v="99", "Microsoft Edge";v="139", "Chromium";v="139"',
            'sec-ch-ua-mobile:?0',
            'sec-ch-ua-platform:"Windows"',
            'sec-fetch-dest:document'
        ];
    }
    
    /**
     * 发送HTTP请求
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @param string $method 请求方法 (GET/POST)
     * @param array $headers 请求头
     * @param bool $multi 是否支持多文件上传
     * @param bool $debug 是否开启调试模式
     * @param array $optsOther 其他CURL选项
     * @return string 响应内容
     */
    public function request($url, $params = [], $method = 'GET', $headers = [], $multi = false, $debug = false, $optsOther = []) {
        // 合并默认请求头
        $headers = !empty($headers) ? $headers : $this->defaultHeaders;
        
        // 设置CURL选项
        $opts = [
            CURLOPT_TIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $headers
        ];
        
        // 根据请求方法设置不同的选项
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $params ? $url . '?' . http_build_query($params) : $url;
                break;
            case 'POST':
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                if ($debug) {
                    exit('不支持的请求方式');
                }
                break;
        }
        
        // 初始化CURL
        $ch = curl_init();
        
        // 合并其他选项
        if ($optsOther && is_array($optsOther)) {
            $opts = $opts + $optsOther;
        }
        
        // 设置CURL选项
        curl_setopt_array($ch, $opts);
        
        // 执行CURL请求
        $data = curl_exec($ch);
        $error = curl_error($ch);
        
        // 关闭CURL
        curl_close($ch);
        
        // 处理错误
        if ($error && $debug) {
            exit('请求出错：' . $error);
        }
        
        return $data;
    }
}